package com.bdqn.tour.servlet.Hzy;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.pojo.User;
import com.bdqn.tour.service.HzyInfoVerifyService;
import com.bdqn.tour.service.impl.HzyInfoVerifyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class InfoVerifyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain;charset=utf-8");

        // 获取参数
        String newPhone = req.getParameter("phone");
        // 从session获取当前用户
        User user = (User) req.getSession().getAttribute("user");

        PrintWriter out = resp.getWriter();
        Map<String, Object> map = new HashMap<>();

        if (user == null) {
            map.put("code", "1001");
            map.put("message", "用户未登录");
        } else {
            try {
                // 更新用户手机号
                HzyInfoVerifyService infoVerifyService = new HzyInfoVerifyServiceImpl();
                user.setIpone(newPhone);
                boolean success = infoVerifyService.updateUser(user);

                if (success) {
                    // 更新session中的用户信息
                    req.getSession().setAttribute("user", user);
                    map.put("code", "0000");
                    map.put("message", "手机号更新成功");
                } else {
                    map.put("code", "2001");
                    map.put("message", "手机号更新失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                map.put("code", "9999");
                map.put("message", "系统错误");
            }
        }

        String json = JSON.toJSONString(map);
        out.print(json);
        out.close();
    }
}
